<!-- 定时任务 -->
<template>
  <div class="app-container">
    <!--列表-->
    <div class="table-container flex-main">
      <div class="table-container-header">
        <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
          <template slot="rightTool">
            <search v-model="listQuery.jobClass" placeholder="请输入任务类名" @search="handleFilter" />
          </template>
        </table-toolbar>
      </div>
      <el-table
        ref="multipleTable"
        :data="list"
        header-cell-class-name="table-header"
        fit
        height="100%"
        highlight-current-row
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @sort-change="sortChange">
        <el-table-column type="selection" width="60" />
        <el-table-column align="center" prop="id" label="#" width="60">
          <template slot-scope="scope">{{ scope.$index+1 }}</template>
        </el-table-column>
        <el-table-column label="任务名称" prop="jobTitle" sortable width="200" />
        <el-table-column label="任务类名" prop="jobClass" width="150" />
        <el-table-column label="任务方法" prop="jobMethod" width="150" />
        <el-table-column label="任务表达式" prop="jobCron" width="260" />
        <el-table-column label="状态" prop="isDisabled" width="80" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              @change="changeIsState(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="任务参数" prop="jobParam" :show-overflow-tooltip="true" min-width="170">
          <template slot-scope="scope">
            {{ scope.row.jobParam }}
          </template>
        </el-table-column>
        <el-table-column label="创建者" prop="createdBy" :show-overflow-tooltip="true" min-width="120">
          <template slot-scope="scope">
            {{ JSON.parse(scope.row.createdBy).realName }}
          </template>
        </el-table-column>
        <el-table-column prop="gmtCreated" sortable label="创建时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtCreated | formatDate }}</template>
        </el-table-column>
        <el-table-column label="更新者" prop="modifyBy" :show-overflow-tooltip="true" min-width="120">
          <template slot-scope="scope">
            {{ scope.row.modifyBy?JSON.parse(scope.row.modifyBy).realName :'-' }}
          </template>
        </el-table-column>
        <el-table-column prop="gmtModified" sortable label="更新时间" width="160">
          <template slot-scope="scope">{{ scope.row.gmtModified | formatDate }}</template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" min-width="200" align="left" header-align="left" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" width="90" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
            <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination_handler">
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="quartzJobRules"
          :model="quartzJobRecord"
          label-position="right"
          label-width="120px">
          <!-- v-if="sideBox.status==='update'" -->
          <el-form-item label="任务名称:" prop="jobTitle">
            <el-input v-model="quartzJobRecord.jobTitle" maxlength="20" show-word-limit placeholder="请输入" />
          </el-form-item>

          <el-form-item label="任务类名:" prop="jobClass">
            <el-select v-model="quartzJobRecord.jobClass" placeholder="请选择" style="width:100%">
              <el-option
                v-for="item in tasksOptions"
                :key="item.simpleName"
                :label="item.simpleName"
                :value="item.simpleName" />
            </el-select>
          </el-form-item>
          <el-form-item label="任务方法名:" prop="jobMethod">
            <el-select v-model="quartzJobRecord.jobMethod" placeholder="请选择" style="width:100%">
              <template v-for="item in tasksOptions">
                <el-option-group
                  v-if="item.simpleName == quartzJobRecord.jobClass"
                  :key="item.simpleName"
                  :label="item.simpleName">
                  <el-option
                    v-for="(value,key) in item.methods"
                    :key="key"
                    :label="key+(value?'(有参)':'(无参)')"
                    :value="key" />
                </el-option-group>
              </template>

            </el-select>
          </el-form-item>
          <el-form-item label="任务表达式:" prop="jobCron">
            <el-input v-model="quartzJobRecord.jobCron" placeholder="请输入" show-word-limit maxlength="100">
              <template slot="append">
                <span class="common-cursor" @click="dialogVisible=true">表达式</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="任务参数:" prop="jobParam">
            <el-input v-model="quartzJobRecord.jobParam" maxlength="100" show-word-limit placeholder="请输入" />
          </el-form-item>

          <el-form-item label="备注:" prop="remark">
            <el-input
              v-model="quartzJobRecord.remark"
              :rows="4"
              type="textarea"
              maxlength="200"
              show-word-limit
              placeholder="请输入" />
          </el-form-item>
        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
    <model-dialog
      title="表达式选择器"
      :visible.sync="dialogVisible"
      width="1015px"
      @close="dialogVisible=!dialogVisible">
      <easy-cron
        v-model="quartzJobRecord.jobCron"
        :exe-start-time="new Date().getTime()"
        :hide-year="false"
        :remote="remote"
        :hide-second="false"
        style="width: 100%" />
      <template slot="footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </template>
    </model-dialog>
  </div>
</template>

<script>
import EasyCron from '@/components/JEasyCron/EasyCron'

export default {
  components: { EasyCron },

  data() {
    return {
      list: null,
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        jobClass: '',
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create' // 对话框状态
      },
      quartzJobRecord: {},
      quartzJobRules: {
        jobClass: [
          { required: true, message: '请输入任务类名', trigger: 'blur' }
        ],
        jobMethod: [
          { required: true, message: '请输入任务方法名', trigger: 'blur' }
        ],
        jobCron: [
          { required: true, message: '请输入任务表达式', trigger: 'blur' }
        ],
        jobTitle: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ]
      },
      tasksOptions: [],
      dialogVisible: false
    }
  },
  watch: {
  },
  created() {
    this.fetchData()
    this.getTaskNameAndMethodNames()
  },
  methods: {
    remote() {

    },
    async getTaskNameAndMethodNames() {
      this.tasksOptions = await this.$store.dispatch('getTaskNameAndMethodNames')
    },
    // 表格自带方法开始
    /**
     * 全选/反选
     */
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /**
     * 表格行数据单击
     */
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /**
     * 表格列排序
     */
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    async fetchData() {
      const response = await this.$store.dispatch('quartzJobPage', this.listQuery)
      this.list = response.records
      this.list.filter((item) => {
        item.status = !item.status
        return true
      })
      this.total = response.total
    },

    /**
     * 搜索
     */
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /**
     * 重置
     */
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        jobClass: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },

    /* 新增*/
    handleCreate() {
      this.quartzJobRecord = {}
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增定时任务'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('quartzJobSave', this.quartzJobRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 编辑*/
    handleUpdate(row) {
      this.quartzJobRecord = Object.assign({}, row) // copy obj
      console.log(this.recordForm)
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑[' + this.quartzJobRecord.jobClass + ']'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },

    updateData() {
      // this.quartzJobRecord.status = null
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.quartzJobRecord)
          this.$store.dispatch('quartzJobUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('quartzJobRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.$modal.msgWarning('请选择要删除的记录')
      }
    },

    changeIsState(row) {
      var temp = Object.assign({}, row) // copy obj

      this.$confirm('您确定' + (temp.status === false ? '停止' : '运行') + '定时任务[' + temp.jobTitle + '], 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        .then(() => {
          const params = {
            id: temp.id,
            status: temp.status
          }
          this.$store.dispatch('quartzJobChangeIsState', params).then(response => {
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {})
        }).catch(() => {
          row.status = !row.status
        })
    }
  }
}
</script>
<style lang="scss" scoped>
</style>

